<template>
  <div class='container'>
    <el-card shadow="never">
      <questions-form v-model="dataChild" @myEvent="hSearch"></questions-form>
      <el-tabs v-model="status" type="card" @tab-click="handleClick">
        <el-tab-pane label="全部" name="all" :disabled="isLoading"></el-tab-pane>
        <el-tab-pane label="待审核" name="0" :disabled="isLoading"></el-tab-pane>
        <el-tab-pane label="已审核" name="1" :disabled="isLoading"></el-tab-pane>
        <el-tab-pane label="已拒绝" name="2" :disabled="isLoading"></el-tab-pane>
      </el-tabs>
      <el-alert
        :title='totalInfo'
        type="info"
        :closable="false"
        style="padding:10px 10px;"
        show-icon>
      </el-alert>
      <el-table
        :data="questions"
        header-align="center"
        v-loading="isLoading"
        style="width: 100%">
        <el-table-column
          prop="number"
          label="试题编号"
          width="250">
        </el-table-column>
        <el-table-column
          prop="subject"
          label="学科"
          width="150">
        </el-table-column>
        <el-table-column
          prop="catalog"
          label="目录"
          width="150">
        </el-table-column>
        <el-table-column
          prop="questionType"
          label="题型"
          width="150">
        </el-table-column>
        <el-table-column
          label="题干"
          width="310">
          <template slot-scope="scope">
          <span v-html="scope.row.question"></span>
        </template>
        </el-table-column>
        <el-table-column
          :formatter="formatTime"
          label="录入时间"
          prop="addDate"
          width="250">
        </el-table-column>
        <el-table-column
          label="难度"
          prop="difficulty"
          width="150">
        </el-table-column>
        <el-table-column
          label="录入人"
          prop="creator"
          width="250">
        </el-table-column>
        <el-table-column
          label="审核状态"
          width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.chkState === 0">待审核</span>
            <span v-else-if="scope.row.chkState === 1">已审核</span>
            <span v-else-if="scope.row.chkState === 2">已拒绝</span>
            <span v-else>wrong</span>
          </template>
        </el-table-column>
        <el-table-column
          label="审核意见"
          prop="chkRemarks"
          width="250">
        </el-table-column>
        <el-table-column
          label="审核人"
          prop="chkUser"
          width="150">
        </el-table-column>
        <el-table-column
          label="发布状态"
          prop="publishState">
          <template slot-scope="scope">
            <span v-if="scope.row.chkState === 0 || scope.row.chkState === 2">待发布</span>
            <span v-else-if="scope.row.chkState === 1 && scope.row.publishState === 1">已发布</span>
            <span v-else-if="scope.row.chkState === 1 && scope.row.publishState === 0">已下架</span>
            <span v-else>wrong</span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="300">
          <template slot-scope="scope">
            <el-button type="text" @click="hPreview(scope.row.id)">预览</el-button>
            <el-button
              type="text"
              @click="hExam(scope.row.id)"
              :disabled="scope.row.chkState ? true : false">审核</el-button>
            <el-button type="text" @click="hModify(scope.row.id)" :disabled="scope.row.publishState === 1">修改</el-button>
            <el-button type="text" @click="hChangePublish(scope.row.id,scope.row.publishState)">
              <span v-if="scope.row.publishState === 1">下架</span>
              <span v-else>上架</span>
            </el-button>
            <el-button type="text" @click="hDel(scope.row.id)" :disabled="scope.row.publishState === 1">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          :disabled="isLoading"
          :page-sizes="[1, 5, 10, 20, 50]"
          :page-size="Number(pagesize)"
          :current-page="Number(page)"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :total="Number(total)"
          layout="prev, pager, next, sizes, jumper">
        </el-pagination>
      </div>
      <questions-preview :questionID="previewData.id" :show="previewData.it"></questions-preview>
      <!-- 题目审核 -->
      <el-dialog title="题目审核" :visible.sync="dialogFormVisible" width="30%" :before-close="handleCloseCheck">
        <el-form :model="formQuestion" :rules="rules" ref="form">
          <el-form-item>
            <el-radio-group v-model="formQuestion.chkState">
              <el-radio :label="1">通过</el-radio>
              <el-radio :label="2">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="chkRemarks">
            <el-input type="textarea" v-model="formQuestion.chkRemarks"></el-input>
          </el-form-item>
          <el-form-item style="margin-top:40px; text-align:right">
            <el-button @click="hCloseCheck">取 消</el-button>
            <el-button type="primary" @click="hConfirmCheck()">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 上架下架 -->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisiblePublish"
        width="30%"
        :before-close="handleClosePublish">
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisiblePublish = false">取 消</el-button>
          <!-- <el-button type="primary" @click="hPublishToggle(id, scope.row.chkState, scope.row.publishState)">确 定</el-button> -->
        </span>
      </el-dialog>
      <!-- 删除 -->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisibleDel"
        width="100%"
        :before-close="handleCloseDel">
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleDel = false">取 消</el-button>
          <el-button type="primary" @click="hDel(id)">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { choice, choiceCheck, remove, choicePublish } from '@/api/hmmm/questions.js'
import QuestionsPreview from './../components/questions-preview.vue'
import QuestionsForm from './questions-form.vue'
// import PageTool from './../components/page-tool.vue'
export default {
  name: 'question-choice',
  components: {
    QuestionsPreview,
    QuestionsForm
    // PageTool
  },
  data () {
    return {
      questions: [],
      isLoading: false,
      total: 0,
      totalInfo: '',
      page: 1,
      pagesize: 5,
      chkState: null,
      dataChild: {}, // 查询条件
      status: 'all',
      dialogFormVisible: false,
      // 题目审核表单
      formQuestion: {
        chkState: 1,
        chkRemarks: '',
        id: 0
      },
      // 预览表单
      previewData: {
        id: '',
        it: false
      },
      dialogVisiblePublish: false,
      dialogVisibleDel: false,
      timer: null,
      rules: {
        chkRemarks: [
          { required: true, message: '请输入审核意见', trigger: 'blur' },
          { min: 1, message: '长度不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.loadChoice()
  },
  // 获取精选题目列表
  methods: {
    async loadChoice () {
      const paramsObj = this.buildParams()
      this.isLoading = true
      try {
        const { data: res } = await choice(paramsObj)
        this.hQuestions(res)
        console.log(this.questions)
        this.isLoading = false
      } catch (err) {
        console.log(err)
      }
    },
    // 处理返回参数 - 依据数据返回正确字符串
    hQuestions (res) {
      this.questions = res.items
      this.total = res.counts
      this.totalInfo = '数据一共' + this.total + '条'
      this.questions.forEach(item => {
        item.questionType = item.questionType.replace('1', '单选').replace('2', '多选').replace('3', '简单')
        item.difficulty = item.difficulty.replace('1', '简单').replace('2', '一般').replace('3', '困难')
      })
    },
    // 查询精选题库
    buildParams () {
      // 从搜索组件中获取搜索条件
      const paramsObj = { ...this.dataChild }
      paramsObj.chkState = this.status === 'all' ? null : this.status
      paramsObj.pagesize = this.pagesize
      paramsObj.page = this.page
      return paramsObj
    },
    // 点击搜索时单独
    hSearch () {
      if (this.timer) return
      this.timer = setTimeout(() => {
        this.doSearch()
        this.timer = null
      }, 500)
    },
    async doSearch () {
      this.isLoading = true
      const paramsObj = { ...this.dataChild }
      paramsObj.pagesize = this.pagesize
      paramsObj.chkState = this.chkState
      try {
        const { data: res } = await choice(paramsObj)
        this.page = paramsObj.page
        this.hQuestions(res)
        this.isLoading = false
      } catch (err) {
        console.log(err)
      }
    },
    // 切换分页的条数
    handleSizeChange (pagesize) {
      this.page = 1
      this.pagesize = pagesize
      this.doThrottle()
    },
    // 切换分页
    handleCurrentChange (page) {
      this.page = page
      this.doThrottle()
    },
    // 预览
    hPreview (id) {
      this.previewData.it = !this.previewData.it
      this.previewData.id = id
    },
    // 弹出审核窗口
    hExam (id) {
      this.dialogFormVisible = true
      this.formQuestion.id = id
    },
    // 发送审核请求
    async doConfirmCheck () {
      try {
        const paramsObj = this.buildConfirmCheck()
        await choiceCheck(paramsObj)
        this.loadChoice(this.buildParams())
        this.$message.success('审核成功')
        // const index = this.questions.findIndex(item => item.id === paramsObj.id)
        // this.questions[index].chkState = paramsObj.chkState
      } catch (err) {
        console.log(err)
        this.$message.error('审核失败')
      }
    },
    buildConfirmCheck () {
      const paramsObj = {}
      paramsObj.chkState = this.formQuestion.chkState
      paramsObj.chkRemarks = this.formQuestion.chkRemarks
      paramsObj.id = this.formQuestion.id
      return paramsObj
    },
    // 点击审核确定按钮
    hConfirmCheck () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 通过验证
          this.doConfirmCheck()
          // 清空发布区域
          this.formQuestionClear()
        } else {
          return false
        }
      })
    },
    hCloseCheck () {
      this.formQuestionClear()
    },
    handleCloseCheck () {
      this.formQuestionClear()
    },
    formQuestionClear () {
      this.formQuestion.chkRemarks = ''
      this.formQuestion.chkState = 1
      this.dialogFormVisible = false
    },
    // 修改 - 跳转到试题录入页面
    hModify (id) {
      this.$router.push('new?id=' + id)
    },
    // 上下架
    async doChangePublish (data) {
      try {
        await choicePublish(data)
      } catch (err) {
        console.log(err)
      }
    },
    // 用户操作上下架
    hChangePublish (id, ps) {
      const publishTip = ps === 1 ? '下架' : '上架'
      const params = {}
      params.id = id
      params.publishState = ps === 1 ? 0 : 1
      this.$confirm('您确定' + publishTip + '这道题目吗 ' + ', 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        this.doChangePublish(params)
        const index = this.questions.findIndex(item => item.id === params.id)
        this.questions[index].publishState = params.publishState
        this.$message.success(publishTip + '成功')
      }).catch(err => {
        console.log(err)
        this.$message.error(publishTip + '失败')
      })
    },
    // 发送请求删除
    async doDel (id) {
      try {
        await remove({ id })
        this.doThrottle()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 用户点击删除
    hDel (id) {
      this.dialogVisibleDel = true
      this.$confirm('您确定删除这道题目吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.doDel(id)
        this.$message.success('删除成功')
      }).catch(err => {
        console.log(err)
        this.$message.error('取消删除')
      })
      console.log(id)
      this.dialogVisibleDel = false
    },
    // 关闭删除弹出层
    handleCloseDel () {
      this.dialogVisibleDel = false
    },
    // hCloseDialog () {
    //   this.dialogVisible = false
    // },
    handleClick () {
      // 判断切换的tab栏如果为全部,就将对应的审核状态转换为null,这样发送数据时不发送对应参数
      console.log(this.status)
      this.chkState = this.status === 'all' ? null : this.status
      this.page = 1
      this.doThrottle()
    },
    // 关闭上下架的弹出层
    handleClosePublish () {
      this.dialogVisiblePublish = false
    },
    // 规范时间
    formatTime (row) {
      const date = new Date(row.addDate)
      var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var month = date.getMonth() + 1
      month = month < 10 ? '0' + month : month
      var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return date.getFullYear() + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds
    },
    // 节流
    doThrottle () {
      if (this.timer) return
      this.timer = setTimeout(() => {
        this.loadChoice()
        this.timer = null
      }, 500)
    }
  }
}
</script>

<style scoped lang='css'>
  .block {
    float: right;
    margin: 20px 0;
  }
  .container {
    margin-left: 10px;
    margin-top: 12px;
    margin-right: 10px;
    padding: 20px;
  }
</style>
